﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using Infragistics.Win;
using Infragistics.Win.UltraWinGrid;
using Infragistics.Win.UltraWinCalcManager;
using Infragistics.Win.CalcEngine;
namespace BYManageInfoSystem
{
    public partial class Frm_FeeInvoiceAndRecvGeneralTab : DockContent
    {
        public class CustomMergedCellEvaluator : Infragistics.Win.UltraWinGrid.IMergedCellEvaluator
        {
            UltraGridColumn m_BaseColumn = null;
            public CustomMergedCellEvaluator(UltraGrid UltraGridTemp)
            {
                foreach (UltraGridColumn column2 in UltraGridTemp.DisplayLayout.Bands[0].Columns)
                {
                    string str = column2.Header.Caption;
                    if (str == "工厂简称")
                    {
                        m_BaseColumn = column2;
                        break;
                    }
                }
            }
            // 合并日期相同的单元格（无需时间精确相同）
            public bool ShouldCellsBeMerged(UltraGridRow row1, UltraGridRow row2, UltraGridColumn column)
            {
                try
                {
                    string str1 = (string)row1.GetCellValue(m_BaseColumn);
                    string str2 = (string)row2.GetCellValue(m_BaseColumn);

                    return str1 == str2;

                    //return true;

                }
                catch (System.Exception ex)
                {
                    //MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return false;
                }


            }

        }
        private DGBY.BLL.FacFeeTabNew m_bllFacFeeTabNew = new DGBY.BLL.FacFeeTabNew();
        private DGBY.BLL.FeeInvoiceAndRecvGeneralTab m_bllFeeInvoiceAndRecvGeneralTab = new DGBY.BLL.FeeInvoiceAndRecvGeneralTab();
        private bool m_bInsertFlag = false;
        private int m_nDelIndex = -1;
        public Frm_FeeInvoiceAndRecvGeneralTab()
        {
            InitializeComponent();
        }

        private void Frm_FeeInvoiceAndRecvGeneralTab_Load(object sender, EventArgs e)
        {
            ClassUltraGridCommonSet.InitUltraWinGridSetting(this.ultraGrid1);
        }
        private void ShowAllRecord()
        {
            int nYear = this.dateTimePicker1.Value.Date.Year;
            int nMonth = this.dateTimePicker1.Value.Date.Month;
            int nYearMonth = 0;
            nYearMonth = nYear * 100 + nMonth;
            DataSet ds = m_bllFacFeeTabNew.GetInvoiceAndRecvGeneralInfo("", nYearMonth);
            ultraGrid1.DataSource = null;

            ultraGrid1.DataSource = ds.Tables[0];
            ultraGrid1.DisplayLayout.Bands[0].Columns[0].Hidden = true;
            ultraGrid1.DisplayLayout.Bands[0].Columns[1].Hidden = true;
        }
        private void buttonShowAll_Click(object sender, EventArgs e)
        {
            ShowAllRecord();
        }
        public static void ultraGrid1_InitializeRowFilter(Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            //ultraGrid1.DisplayLayout.Override.RowSizing = RowSizing.AutoFree;
            //foreach (UltraGridColumn ugc in ultraGrid1.DisplayLayout.Bands[0].Columns)
            //    ugc.PerformAutoResize();
            // FILTER ROW FUNCTIONALITY RELATED ULTRAGRID SETTINGS
            //e.Layout.Override.RowFilterAction = RowFilterAction.DisableFilteredOutRows;
            // ----------------------------------------------------------------------------------
            // Enable the the filter row user interface by setting the FilterUIType to FilterRow.
            e.Layout.Override.FilterUIType = FilterUIType.FilterRow;
            //e.Layout.Override.RowFilterMode = RowFilterMode.AllRowsInBand;
            // FilterEvaluationTrigger specifies when UltraGrid applies the filter criteria typed 
            // into a filter row. Default is OnCellValueChange which will cause the UltraGrid to
            // re-filter the data as soon as the user modifies the value of a filter cell.
            e.Layout.Override.FilterEvaluationTrigger = FilterEvaluationTrigger.OnCellValueChange;
            //e.Layout.Override.RowFilterMode = RowFilterMode.AllRowsInBand;
            // By default the UltraGrid selects the type of the filter operand editor based on
            // the column's DataType. For DateTime and boolean columns it uses the column's editors.
            // For other column types it uses the Combo. You can explicitly specify the operand
            // editor style by setting the FilterOperandStyle on the override or the individual
            // columns.

            e.Layout.Override.FilterOperandStyle = FilterOperandStyle.DropDownList;

            // By default UltraGrid displays user interface for selecting the filter operator. 
            // You can set the FilterOperatorLocation to hide this user interface. This
            // property is available on column as well so it can be controlled on a per column
            // basis. Default is WithOperand. This property is exposed off the column as well.
            e.Layout.Override.FilterOperatorLocation = FilterOperatorLocation.WithOperand;

            // By default the UltraGrid uses StartsWith as the filter operator. You use
            // the FilterOperatorDefaultValue property to specify a different filter operator
            // to use. This is the default or the initial filter operator value of the cells
            // in filter row. If filter operator user interface is enabled (FilterOperatorLocation
            // is not set to None) then that ui will be initialized to the value of this
            // property. The user can then change the operator as he/she chooses via the operator
            // drop down.
            e.Layout.Override.FilterOperatorDefaultValue = FilterOperatorDefaultValue.StartsWith;

            // FilterOperatorDropDownItems property can be used to control the options provided
            // to the user for selecting the filter operator. By default UltraGrid bases 
            // what operator options to provide on the column's data type. This property is
            // avaibale on the column as well.
            //e.Layout.Override.FilterOperatorDropDownItems = FilterOperatorDropDownItems.All;

            // By default UltraGrid displays a clear button in each cell of the filter row
            // as well as in the row selector of the filter row. When the user clicks this
            // button the associated filter criteria is cleared. You can use the 
            // FilterClearButtonLocation property to control if and where the filter clear
            // buttons are displayed.
            e.Layout.Override.FilterClearButtonLocation = FilterClearButtonLocation.RowAndCell;

            // Appearance of the filter row can be controlled using the FilterRowAppearance proeprty.
            e.Layout.Override.FilterRowAppearance.BackColor = Color.LightYellow;

            // You can use the FilterRowPrompt to display a prompt in the filter row. By default
            // UltraGrid does not display any prompt in the filter row.
            e.Layout.Override.FilterRowPrompt = "Click here to filter data...";

            // You can use the FilterRowPromptAppearance to change the appearance of the prompt.
            // By default the prompt is transparent and uses the same fore color as the filter row.
            // You can make it non-transparent by setting the appearance' BackColorAlpha property 
            // or by setting the BackColor to a desired value.
            e.Layout.Override.FilterRowPromptAppearance.BackColorAlpha = Alpha.Opaque;

            // By default the prompt is spread across multiple cells if it's bigger than the
            // first cell. You can confine the prompt to a particular cell by setting the
            // SpecialRowPromptField property off the band to the key of a column.
            //e.Layout.Bands[0].SpecialRowPromptField = e.Layout.Bands[0].Columns[0].Key;

            // Display a separator between the filter row other rows. SpecialRowSeparator property 
            // can be used to display separators between various 'special' rows, including for the
            // filter row. This property is a flagged enum property so it can take multiple values.
            e.Layout.Override.SpecialRowSeparator = SpecialRowSeparator.FilterRow;

            // You can control the appearance of the separator using the SpecialRowSeparatorAppearance
            // property.
            e.Layout.Override.SpecialRowSeparatorAppearance.BackColor = Color.FromArgb(233, 242, 199);

            //   UltraGridBand band = e.Layout.Bands[0];
            //   band.ColumnFilters["原币金额"].FilterConditions.Clear();
            //   band.ColumnFilters["原币金额"].FilterConditions.Add(

            //FilterComparisionOperator.GreaterThan, 5);
            //   band.ColumnFilters["原币金额"].FilterConditions.Add(

            //FilterComparisionOperator.LessThan, 10);
            //   band.ColumnFilters["原币金额"].LogicalOperator = FilterLogicalOperator.And;
        }

        private void ultraGrid1_InitializeLayout(object sender, InitializeLayoutEventArgs e)
        {
            if (this.checkBox1.Checked == true)
                ultraGrid1_InitializeRowFilter(e);
            else
                ClassUltraGridCommonSet.ultraGrid1_InitializeRowFilter(e);

            Infragistics.Win.UltraWinCalcManager.UltraCalcManager calcManager;
			calcManager = new Infragistics.Win.UltraWinCalcManager.UltraCalcManager( this.Container );
			e.Layout.Grid.CalcManager = calcManager;



            SummarySettings averageSummary =
e.Layout.Bands[0].Summaries.Add(
"应收金额",
SummaryType.Sum,
e.Layout.Bands[0].Columns["应收金额"]);
            averageSummary.SummaryPosition = SummaryPosition.UseSummaryPositionColumn;
            averageSummary.SummaryPositionColumn = averageSummary.SourceColumn;
            averageSummary.DisplayFormat = "{0:.##}";
            averageSummary.Band.Override.SummaryFooterCaptionVisible = DefaultableBoolean.False;
            averageSummary.Band.Override.BorderStyleSummaryFooter = UIElementBorderStyle.None;
            averageSummary.SummaryDisplayArea = SummaryDisplayAreas.TopFixed;

            averageSummary =
e.Layout.Bands[0].Summaries.Add(
"票据金额",
SummaryType.Sum,
e.Layout.Bands[0].Columns["票据金额"]);
            averageSummary.SummaryPosition = SummaryPosition.UseSummaryPositionColumn;
            averageSummary.SummaryPositionColumn = averageSummary.SourceColumn;
            averageSummary.DisplayFormat = "{0:.##}";
            averageSummary.Band.Override.SummaryFooterCaptionVisible = DefaultableBoolean.False;
            averageSummary.Band.Override.BorderStyleSummaryFooter = UIElementBorderStyle.None;
            averageSummary.SummaryDisplayArea = SummaryDisplayAreas.TopFixed;

            averageSummary =
e.Layout.Bands[0].Summaries.Add(
"实收金额",
SummaryType.Sum,
e.Layout.Bands[0].Columns["实收金额"]);
            averageSummary.SummaryPosition = SummaryPosition.UseSummaryPositionColumn;
            averageSummary.SummaryPositionColumn = averageSummary.SourceColumn;
            averageSummary.DisplayFormat = "{0:.##}";
            averageSummary.Band.Override.SummaryFooterCaptionVisible = DefaultableBoolean.False;
            averageSummary.Band.Override.BorderStyleSummaryFooter = UIElementBorderStyle.None;
            averageSummary.SummaryDisplayArea = SummaryDisplayAreas.TopFixed;

            averageSummary =
e.Layout.Bands[0].Summaries.Add(
"应收未收金额",
SummaryType.Sum,
e.Layout.Bands[0].Columns["应收未收金额"]);
            averageSummary.SummaryPosition = SummaryPosition.UseSummaryPositionColumn;
            averageSummary.SummaryPositionColumn = averageSummary.SourceColumn;
            averageSummary.DisplayFormat = "{0:.##}";
            averageSummary.Band.Override.SummaryFooterCaptionVisible = DefaultableBoolean.False;
            averageSummary.Band.Override.BorderStyleSummaryFooter = UIElementBorderStyle.None;
            averageSummary.SummaryDisplayArea = SummaryDisplayAreas.TopFixed;
        }

        private void buttonExportToExcel_Click(object sender, EventArgs e)
        {
            DataTable dt = (DataTable)ultraGrid1.DataSource;

            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    SaveFileDialog sfd = new SaveFileDialog();
                    sfd.Filter = "Excel文件(*.xls)|*.xls";
                    string outFile = "";

                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        outFile = sfd.FileName;
                    }
                    else
                    {
                        return;
                    }

                    ultraGridExcelExporter1.Export(ultraGrid1, outFile);
                }
            }
        }



        private void ultraGrid1_AfterCellActivate(object sender, EventArgs e)
        {
            int iIndex = this.ultraGrid1.ActiveCell.Row.Index;
            if (iIndex < 0)
                return;
            m_nDelIndex = ultraGrid1.ActiveRow.Index;
        }

        private void ultraGrid1_BeforeRowUpdate(object sender, CancelableRowEventArgs e)
        {
            try
            {
                UltraGridRow CurrentUGR;
                CurrentUGR = ultraGrid1.Rows[e.Row.Index];

                if (m_bInsertFlag)
                {
                    ultraGrid1.Rows[e.Row.Index].Cells[2].Activation = Activation.ActivateOnly;
                    m_bInsertFlag = false;

                }
                else//修改
                {

                    ModifyGoodsDetail(e.Row.Index);

                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
        }

        private bool ModifyGoodsDetail(int nRowIndex)
        {

            try
            {
                UltraGridRow CurrentUGR;
                CurrentUGR = ultraGrid1.Rows[nRowIndex];
                //int nFeeInvoiceAndRecvGeneralTabID = Convert.ToInt32(CurrentUGR.Cells["FeeInvoiceAndRecvGeneralTabId"].Value.ToString(), 10);
                int nYear = this.dateTimePicker1.Value.Date.Year;
                int nMonth = this.dateTimePicker1.Value.Date.Month;
                int nYearMonth = 0;
                nYearMonth = nYear * 100 + nMonth;

                int nFacID = (int)CurrentUGR.Cells["FactoryDataTabID"].Value;
                DataSet ds = m_bllFeeInvoiceAndRecvGeneralTab.GetList("FactoryDataTabID = '" + nFacID + "'");
                if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    int nFeeInvoiceAndRecvGeneralTabID = (int)ds.Tables[0].Rows[0]["FeeInvoiceAndRecvGeneralTabID"];
                    DGBY.Model.FeeInvoiceAndRecvGeneralTab modelFeeInvoiceAndRecvGeneralTab
                    = m_bllFeeInvoiceAndRecvGeneralTab.GetModel(nFeeInvoiceAndRecvGeneralTabID);

                    modelFeeInvoiceAndRecvGeneralTab.InvoicePostDate = Convert.ToDateTime(CurrentUGR.Cells["寄出发票日期"].Value.ToString());
                    modelFeeInvoiceAndRecvGeneralTab.SalesManSendSheetDate = Convert.ToDateTime(CurrentUGR.Cells["业务员发账单日期"].Value.ToString());
                    modelFeeInvoiceAndRecvGeneralTab.ExpressNo = CurrentUGR.Cells["快递号"].Value.ToString();
                    modelFeeInvoiceAndRecvGeneralTab.Note = "";

                    modelFeeInvoiceAndRecvGeneralTab.ShouldRecvYearMonth = nYearMonth;
                    modelFeeInvoiceAndRecvGeneralTab.FactoryDataTabID = (int)CurrentUGR.Cells["FactoryDataTabID"].Value;
                    m_bllFeeInvoiceAndRecvGeneralTab.Update(modelFeeInvoiceAndRecvGeneralTab);
                }
                else
                {
                    DGBY.Model.FeeInvoiceAndRecvGeneralTab modelFeeInvoiceAndRecvGeneralTabNew = new DGBY.Model.FeeInvoiceAndRecvGeneralTab();
                    modelFeeInvoiceAndRecvGeneralTabNew.InvoicePostDate = Convert.ToDateTime(CurrentUGR.Cells["寄出发票日期"].Value.ToString());
                    modelFeeInvoiceAndRecvGeneralTabNew.SalesManSendSheetDate = Convert.ToDateTime(CurrentUGR.Cells["业务员发账单日期"].Value.ToString());
                    modelFeeInvoiceAndRecvGeneralTabNew.ExpressNo = CurrentUGR.Cells["快递号"].Value.ToString();
                    modelFeeInvoiceAndRecvGeneralTabNew.Note = "";

                    modelFeeInvoiceAndRecvGeneralTabNew.ShouldRecvYearMonth = nYearMonth;
                    modelFeeInvoiceAndRecvGeneralTabNew.FactoryDataTabID = (int)CurrentUGR.Cells["FactoryDataTabID"].Value;

                    modelFeeInvoiceAndRecvGeneralTabNew.intFiledReserv1 = 0;
                    modelFeeInvoiceAndRecvGeneralTabNew.intFiledReserv2 = 0;

                    modelFeeInvoiceAndRecvGeneralTabNew.bitFiledReserv1 = false;
                    modelFeeInvoiceAndRecvGeneralTabNew.bitFiledReserv2 = false;
                    modelFeeInvoiceAndRecvGeneralTabNew.stringFiledReserv1 = "";
                    modelFeeInvoiceAndRecvGeneralTabNew.stringFiledReserv2 = "";
                    modelFeeInvoiceAndRecvGeneralTabNew.datetimeFiledReserv1 = System.DateTime.Now.Date;
                    modelFeeInvoiceAndRecvGeneralTabNew.datetimeFiledReserv2 = System.DateTime.Now.Date;
                    modelFeeInvoiceAndRecvGeneralTabNew.decimalFiledReserv1 = 0;
                    modelFeeInvoiceAndRecvGeneralTabNew.decimalFiledReserv2 = 0;

                    m_bllFeeInvoiceAndRecvGeneralTab.Add(modelFeeInvoiceAndRecvGeneralTabNew);


                }
                //modelFacFeeTabNew.SJJinE = Convert.ToDecimal(CurrentUGR.Cells["商检金额"].Value.ToString());


                ShowAllRecord();
                return true;

            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }

        private void ultraGrid1_InitializeRow(object sender, InitializeRowEventArgs e)
        {
            ultraGrid1.DisplayLayout.Override.CellAppearance.TextHAlign = HAlign.Center;
            ultraGrid1.DisplayLayout.Override.CellAppearance.TextVAlign = VAlign.Middle;
            ultraGrid1.DisplayLayout.Override.MergedCellAppearance.TextHAlign = HAlign.Center;
            ultraGrid1.DisplayLayout.Override.MergedCellAppearance.TextVAlign = VAlign.Middle;

            ultraGrid1.DisplayLayout.Bands[0].Columns["经营单位"].MergedCellStyle = MergedCellStyle.Always;
            ultraGrid1.DisplayLayout.Bands[0].Columns["经营单位"].MergedCellEvaluator = new
   CustomMergedCellEvaluator(this.ultraGrid1);

            ultraGrid1.DisplayLayout.Bands[0].Columns["货品种类"].MergedCellStyle = MergedCellStyle.Always;
            ultraGrid1.DisplayLayout.Bands[0].Columns["货品种类"].MergedCellEvaluator = new
   CustomMergedCellEvaluator(this.ultraGrid1);

            ultraGrid1.DisplayLayout.Bands[0].Columns["部门名称"].MergedCellStyle = MergedCellStyle.Always;
            ultraGrid1.DisplayLayout.Bands[0].Columns["部门名称"].MergedCellEvaluator = new
   CustomMergedCellEvaluator(this.ultraGrid1);
            ultraGrid1.DisplayLayout.Bands[0].Columns["工厂简称"].MergedCellStyle = MergedCellStyle.Always;
            ultraGrid1.DisplayLayout.Bands[0].Columns["工厂简称"].MergedCellEvaluator = new
   CustomMergedCellEvaluator(this.ultraGrid1);

            ultraGrid1.DisplayLayout.Bands[0].Columns["应收费用合计"].MergedCellStyle = MergedCellStyle.Always;
            ultraGrid1.DisplayLayout.Bands[0].Columns["应收费用合计"].MergedCellEvaluator = new
   CustomMergedCellEvaluator(this.ultraGrid1);

            ultraGrid1.DisplayLayout.Bands[0].Columns["应收未收金额"].MergedCellStyle = MergedCellStyle.Always;
            ultraGrid1.DisplayLayout.Bands[0].Columns["应收未收金额"].MergedCellEvaluator = new
   CustomMergedCellEvaluator(this.ultraGrid1);

            ultraGrid1.DisplayLayout.Bands[0].Columns["实收金额"].MergedCellStyle = MergedCellStyle.Always;
            ultraGrid1.DisplayLayout.Bands[0].Columns["实收金额"].MergedCellEvaluator = new
   CustomMergedCellEvaluator(this.ultraGrid1);
   //         ultraGrid1.DisplayLayout.Bands[0].Columns["实际收款差额"].MergedCellStyle = MergedCellStyle.Always;
   //         ultraGrid1.DisplayLayout.Bands[0].Columns["实际收款差额"].MergedCellEvaluator = new
   //CustomMergedCellEvaluator(this.ultraGrid1);
            ultraGrid1.DisplayLayout.Bands[0].Columns["业务员发账单日期"].MergedCellStyle = MergedCellStyle.Always;
            ultraGrid1.DisplayLayout.Bands[0].Columns["业务员发账单日期"].MergedCellEvaluator = new
   CustomMergedCellEvaluator(this.ultraGrid1);
            ultraGrid1.DisplayLayout.Bands[0].Columns["寄出发票日期"].MergedCellStyle = MergedCellStyle.Always;
            ultraGrid1.DisplayLayout.Bands[0].Columns["寄出发票日期"].MergedCellEvaluator = new
   CustomMergedCellEvaluator(this.ultraGrid1);
            ultraGrid1.DisplayLayout.Bands[0].Columns["快递号"].MergedCellStyle = MergedCellStyle.Always;
            ultraGrid1.DisplayLayout.Bands[0].Columns["快递号"].MergedCellEvaluator = new
   CustomMergedCellEvaluator(this.ultraGrid1);
        }


    }
}
